package com.example.demo

import android.content.Context
import android.util.Log.println
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.book.repository.BookDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Singleton

@InstallIn(SingletonComponent::class)
@Module
class DemoDatabaseModule {

    @Provides
    @Singleton
    fun demoDatabase(@ApplicationContext context: Context): DemoDatabase {
        return DemoDatabaseModule.getDatabase(context,CoroutineScope(SupervisorJob()))
    }

    private class DemoDatabaseCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {

        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)

            INSTANCE?.let { demoDatabase ->
                scope.launch {
//                    populateDatabase(demoDatabase.bookDao())
                }
            }
        }

        //initialize database with default data
        suspend fun populateDatabase(bookDao: BookDao) {
//            bookDao.deleteAll()
//            bookDao.insert(Book("A-2021","Android","100"), Book("B-2021","Java","199"))
        }
    }

    private class DemoQueryCallback : RoomDatabase.QueryCallback {
        override fun onQuery(sqlQuery: String, bindArgs: MutableList<Any>) {
            //println("QueryCallback: sqlQuery=${sqlQuery}")
        }
    }

    companion object {
        //Singleton prevents multiple instances of database opening at the same time.
        @Volatile
        private var INSTANCE : DemoDatabase? = null

        fun getDatabase(context: Context, scope: CoroutineScope): DemoDatabase {
            return INSTANCE ?: synchronized(this){
                val instance = Room.databaseBuilder(context.applicationContext, DemoDatabase::class.java,"demo_database.db")
                    .addCallback(DemoDatabaseCallback(scope))
                    .allowMainThreadQueries()
                    .build()

                INSTANCE = instance

                instance
            }
        }
    }
}